package com.engineering.elink.redis;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import com.engineering.elink.util.JSONUtil;

import redis.clients.jedis.Jedis;

/**
 * 封装对redis的数据存取操作
 * @author hxjxiaojun
 *
 */
public class RedisUtil {
	
	/**
	 * 存入seed-object对象
	 * @param dbNum 选择的redis池
	 * @param key 主键
	 * @param obj  value 
	 * @param validTime 有效时间
	 */
	public static Boolean putSeedObjectMap(int dbNum, String key, Object obj,int validTime) {
		System.out.println("fun:putSeedObjectMap=" + dbNum);
		Boolean flag = false;
		Jedis jedis = MyJedis.getJedisInstance();
		if (getObjectBySeed(dbNum, key) != null) {
			jedis.del(key.getBytes());// 删除旧数据
		}
		jedis.select(dbNum);
		String str = null;
		if (obj != null && obj instanceof Map) {
			System.out.println("转成map");
			str = jedis.set(key.getBytes(),JSONUtil.mapToString((Map<?, ?>)obj).getBytes());// 覆盖数据
		}else {
			System.out.println("转成序列化");
			str = jedis.set(key.getBytes(),SerializeUtil.serialize(obj) );// 覆盖数据
		}
		if ("OK".contentEquals(str)) {
            flag = true; 
		}
		jedis.expire(key, validTime);

		MyJedis.returnJedis(jedis);

		return flag;
	}
	
	/**
	 * 根据seed获取Object
	 * @param dbNum
	 * @param key
	 * @return
	 */
	public static Object getObjectBySeed(int dbNum, String key) {
		System.out.println("fun:getObjectBySeed=" + dbNum);
		Jedis jedis = MyJedis.getJedisInstance();
		jedis.select(dbNum);
		byte[] object = jedis.get(key.getBytes());
		MyJedis.returnJedis(jedis);
		Map<String, Object> map = new HashMap<String, Object>();
		if(jedis.ttl(key) == -1){ //超过有效期
			return jedis.ttl(key);
		}else{
			if (object != null) {
				try {
					map.put("object",JSONUtil.stringToMap(new String(object)));
				} catch (IOException e) {
					// TODO Auto-generated catch block
//					e.printStackTrace();
					System.out.println("捕捉异常");
					map.put("object", SerializeUtil.unserialize(object));
				}
			} else {
				map.put("object", null);
			}
			map.put("ttl",jedis.ttl(key));
			return map;
		}
	}
	
	/**
	 * 根据seed删除Object对象
	 * @param dbNum
	 * @param key
	 */
	public static Long delObjectBySeed(int dbNum, String key) {
		Jedis jedis = MyJedis.getJedisInstance();
		jedis.select(dbNum);
		Long l = jedis.del(key.getBytes());
		MyJedis.returnJedis(jedis);
		return l;
	}

	public static void main(String[] args) {
		putSeedObjectMap(11, "key", "dajiahao",1111); 
	}
}